// 切换登录/注册表单
function switchTab(tab) {
    const tabs = document.querySelectorAll('.auth-tab');
    const forms = document.querySelectorAll('.auth-form');

    tabs.forEach(t => t.classList.remove('active'));
    forms.forEach(f => f.classList.remove('active'));

    tab.classList.add('active');
    document.getElementById(tab.dataset.form).classList.add('active');
}

// 检查密码强度
function checkPasswordStrength(password) {
    if (password.length < 6) {
        return 'weak';
    } else if (password.length < 10) {
        return 'medium';
    } else {
        return 'strong';
    }
}

// 验证邮箱格式
function validateEmail(email) {
    const emailRegex = /^[a-zA-Z0-9._%+-]+@(pku\.edu\.cn|stu\.pku\.edu\.cn)$/;
    return emailRegex.test(email);
}

// 密码加密函数
function encryptPassword(password) {
    // 使用SHA-256算法进行加密
    return CryptoJS.SHA256(password).toString();
}

// 登录
async function login() {
    const email = document.getElementById('login-email').value;
    const password = document.getElementById('login-password').value;

    if (!email || !password) {
        showMessage('login-message', '请填写所有字段', true);
        return;
    }

    if (!validateEmail(email)) {
        showMessage('login-message', '请输入有效的北大邮箱地址', true);
        return;
    }

    try {
        const response = await fetch('/api/login', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json'
            },
            body: JSON.stringify({
                email,
                password: encryptPassword(password)
            })
        });

        const data = await response.json();

        if (response.ok) {
            showMessage('login-message', '登录成功');
            setTimeout(() => {
                window.location.href = '/index.html';
            }, 1000);
        } else {
            showMessage('login-message', data.error || '登录失败', true);
        }
    } catch (error) {
        console.error('登录失败:', error);
        showMessage('login-message', '登录失败，请重试', true);
    }
}

// 发送验证码
async function sendVerificationCode() {
    const email = document.getElementById('register-email').value;
    const sendButton = document.getElementById('send-code-button');

    if (!email) {
        showMessage('register-message', '请先输入邮箱地址', true);
        return;
    }

    if (!validateEmail(email)) {
        showMessage('register-message', '请输入有效的北大邮箱地址', true);
        return;
    }

    try {
        // 禁用发送按钮并开始倒计时
        sendButton.disabled = true;
        let countdown = 60;
        sendButton.textContent = `${countdown}秒后重试`;
        sendButton.classList.add('counting');

        const timer = setInterval(() => {
            countdown--;
            sendButton.textContent = `${countdown}秒后重试`;
            if (countdown <= 0) {
                clearInterval(timer);
                sendButton.disabled = false;
                sendButton.textContent = '发送验证码';
                sendButton.classList.remove('counting');
            }
        }, 1000);

        const response = await fetch('/api/send-verification-code', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json'
            },
            body: JSON.stringify({ email })
        });

        const data = await response.json();

        if (response.ok) {
            showMessage('register-message', '验证码已发送，请查收邮件');
        } else {
            showMessage('register-message', data.error || '发送验证码失败', true);
            // 发送失败时重置按钮状态
            clearInterval(timer);
            sendButton.disabled = false;
            sendButton.textContent = '发送验证码';
            sendButton.classList.remove('counting');
        }
    } catch (error) {
        console.error('发送验证码失败:', error);
        showMessage('register-message', '发送验证码失败，请重试', true);
        // 发生错误时重置按钮状态
        sendButton.disabled = false;
        sendButton.textContent = '发送验证码';
        sendButton.classList.remove('counting');
    }
}

// 修改注册函数
async function register() {
    const email = document.getElementById('register-email').value;
    const password = document.getElementById('register-password').value;
    const confirmPassword = document.getElementById('register-confirm-password').value;
    const verificationCode = document.getElementById('verification-code').value;

    if (!email || !password || !confirmPassword || !verificationCode) {
        showMessage('register-message', '请填写所有字段', true);
        return;
    }

    if (!validateEmail(email)) {
        showMessage('register-message', '请输入有效的北大邮箱地址', true);
        return;
    }

    if (password !== confirmPassword) {
        showMessage('register-message', '两次输入的密码不一致', true);
        return;
    }

    const strength = checkPasswordStrength(password);
    if (strength === 'weak') {
        showMessage('register-message', '密码强度太弱，请使用更复杂的密码', true);
        return;
    }

    try {
        const response = await fetch('/api/register', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json'
            },
            body: JSON.stringify({
                email,
                password: encryptPassword(password),
                nickname: email.split('@')[0],
                description: '',
                verification_code: verificationCode
            })
        });

        const data = await response.json();

        if (response.ok) {
            showMessage('register-message', '注册成功，请登录');
            setTimeout(() => {
                switchTab(document.querySelector('[data-form="login-form"]'));
            }, 1000);
        } else {
            showMessage('register-message', data.error || '注册失败', true);
        }
    } catch (error) {
        console.error('注册失败:', error);
        showMessage('register-message', '注册失败，请重试', true);
    }
}

// 监听密码输入，显示密码强度
document.getElementById('register-password').addEventListener('input', function (e) {
    const strength = checkPasswordStrength(e.target.value);
    const strengthElement = document.getElementById('password-strength');
    strengthElement.textContent = `密码强度: ${strength === 'weak' ? '弱' : strength === 'medium' ? '中' : '强'}`;
    strengthElement.className = `password-strength ${strength}`;
});

// 显示修改密码表单
function showChangePasswordForm() {
    document.getElementById('login-form').classList.remove('active');
    document.getElementById('register-form').classList.remove('active');
    document.getElementById('change-password-form').classList.add('active');
    
    // 更新标签页状态
    document.querySelectorAll('.auth-tab').forEach(tab => tab.classList.remove('active'));
}

// 显示登录表单
function showLoginForm() {
    document.getElementById('change-password-form').classList.remove('active');
    document.getElementById('register-form').classList.remove('active');
    document.getElementById('login-form').classList.add('active');
    
    // 更新标签页状态
    document.querySelector('[data-form="login-form"]').classList.add('active');
}

// 修改密码
async function changePassword() {
    const email = document.getElementById('change-password-email').value;
    const oldPassword = document.getElementById('change-password-old').value;
    const newPassword = document.getElementById('change-password-new').value;
    const confirmPassword = document.getElementById('change-password-confirm').value;

    if (!email || !oldPassword || !newPassword || !confirmPassword) {
        showMessage('change-password-message', '请填写所有字段', true);
        return;
    }

    if (!validateEmail(email)) {
        showMessage('change-password-message', '请输入有效的北大邮箱地址', true);
        return;
    }

    if (newPassword !== confirmPassword) {
        showMessage('change-password-message', '两次输入的新密码不一致', true);
        return;
    }

    const strength = checkPasswordStrength(newPassword);
    if (strength === 'weak') {
        showMessage('change-password-message', '新密码强度太弱，请使用更复杂的密码', true);
        return;
    }

    try {
        const response = await fetch('/api/user/password', {
            method: 'PUT',
            headers: {
                'Content-Type': 'application/json'
            },
            body: JSON.stringify({
                user: email,
                old_password: encryptPassword(oldPassword),
                new_password: encryptPassword(newPassword)
            })
        });

        const data = await response.json();

        if (response.ok) {
            showMessage('change-password-message', '密码修改成功，请重新登录');
            setTimeout(() => {
                showLoginForm();
            }, 1500);
        } else {
            showMessage('change-password-message', data.error || '密码修改失败', true);
        }
    } catch (error) {
        console.error('修改密码失败:', error);
        showMessage('change-password-message', '修改密码失败，请重试', true);
    }
}

// 监听新密码输入，显示密码强度
document.getElementById('change-password-new').addEventListener('input', function (e) {
    const strength = checkPasswordStrength(e.target.value);
    const strengthElement = document.getElementById('change-password-strength');
    strengthElement.textContent = `密码强度: ${strength === 'weak' ? '弱' : strength === 'medium' ? '中' : '强'}`;
    strengthElement.className = `password-strength ${strength}`;
}); 